#pragma once

#include <iostream>
#include <memory>
#include <string>
#include <cstring>
#include <strings.h>
#include <unistd.h>
#include <functional>
#include <memory>
#include <list>

#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <pthread.h>
#include <algorithm>

#include "Common.hpp"

static const uint16_t defaultport = 8888;

class InetAddr
{
private:
    void IpNetToHost()
    {
        char buffer[64];
        const char *ip = ::inet_ntop(AF_INET, &_net_addr.sin_addr.s_addr, buffer, sizeof(_net_addr));
        _ip = ip;
    }

    void PortNetToHost()
    {
        _port = ::ntohs(_net_addr.sin_port);
    }

public:
    InetAddr() : _ip(""), _port(defaultport)
    {
    }

    InetAddr(const struct sockaddr_in &peer) : _net_addr(peer)
    {
        IpNetToHost();
        PortNetToHost();
    }

    InetAddr(uint16_t port)
    {
        _net_addr.sin_family = AF_INET;
        _net_addr.sin_port = ::htons(port);
        _net_addr.sin_addr.s_addr = INADDR_ANY;
    }

    bool operator==(const InetAddr &peer)
    {
        return _port == peer._port && _ip == peer._ip;
    }


    void SetAddr(const sockaddr_in& peer)
    {
        _net_addr = peer;
        IpNetToHost();
        PortNetToHost();
    }

    struct sockaddr *NetAddr() { return CONV(&_net_addr); }
    socklen_t AddrLen() { return sizeof(_net_addr); }
    uint16_t GetPort() { return _port; }
    std::string GetIp() { return _ip; }
    ~InetAddr()
    {
    }

private:
    std::string _ip;
    uint16_t _port;
    struct sockaddr_in _net_addr;
};